<?php
/**
 * @package Autogenerator for Joomla!
 * @version 3.0.0
 * @author Truong Cong Duc <truongcongduc4@gmail.com>
 * @link autogenerator.blogspot.com
 * @copyright (c) 2013, Truong Cong Duc
 * @license GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

require_once JPATH_COMPONENT_ADMINISTRATOR . '/helpers/autogenerator.php';

class AutogeneratorModelImport extends JModelAdmin
{

    protected $oApplication;
    protected $text_prefix = 'COM_AUTOGENERATOR';
    /**
     *
     * @var AutogeneratorModelTable 
     */
    public $oModelTable;
    /**
     *
     * @var AutogeneratorModelMvc 
     */
    public $oModelMVC;
    /**
     *
     * @var AutogeneratorModelField 
     */
    public $oModelField;
    public function __construct($oConfig = array())
    {
        parent::__construct($oConfig);
        $this->oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $this->oModelMVC = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');
        $this->oModelField = JModelLegacy::getInstance('Field', 'AutogeneratorModel');
        $this->oApplication = JFactory::getApplication();
    }

    public function getForm($aData = array(), $mLoadData = true)
    {
        $oForm = $this->loadForm('com_autogenerator.import', 'import', array('control' => 'jform', 'load_data' => $mLoadData));

        if (empty($oForm))
        {
            return false;
        }

        return $oForm;
    }

    public function getTable($sType = 'Table', $sPrefix = 'AutogeneratorTable', $sConfig = array())
    {
        $oTable = JTable::getInstance($sType, $sPrefix, $sConfig);
        $oTable instanceof AutogeneratorTableTable;
        return $oTable;
    }

    protected function loadFormData()
    {
        $aData = $this->oApplication->getUserState('com_autogenerator.edit.import.data', array());

        if (empty($aData))
        {
            $aData = $this->getItem();
        }

        $aData->component_id = $this->oApplication->input->getInt('iComponentId');

        return $aData;
    }

    public function store($aData)
    {
        $oTable = $this->getTable();

        $sKey = $oTable->getKeyName();

        $iPrimaryKey = (!empty($aData[$sKey])) ? $aData[$sKey] : 0;

        $bIsNew = true;

        // Allow an exception to be thrown.
        try
        {
            // Load the row if saving an existing record.
            if ($iPrimaryKey > 0)
            {
                $oTable->load($iPrimaryKey);

                $bIsNew = false;
            }

            // Bind the data.
            if (!$oTable->bind($aData))
            {
                $this->setError($oTable->getError());

                return false;
            }

            // Prepare the row for saving
            $this->prepareTable($oTable);

            // Check the data.
            if (!$oTable->check())
            {
                $this->setError($oTable->getError());
                return false;
            }

            // Store the data.
            if (!$oTable->store())
            {
                $this->setError($oTable->getError());
                return false;
            }

            // Clean the cache.
            $this->cleanCache();
        }
        catch (Exception $oException)
        {
            $this->setError($oException->getMessage());
            
            return false;
        }

        return $oTable->{$sKey};
    }

    public function save($aData)
    {
        foreach ($aData['tables'] as $sTable)
        {
            $aTemp = array(
                'component_id' => $aData['component_id'],
                'title' => $sTable,
                'sql_table_name' => $sTable
            );

            $iTableId = $this->store($aTemp);
        
            if ($iTableId == false)
            {
                return false;
            }
            
            // Get all fields of the table.
            $aFields = $this->oModelTable->getAllFieldsInDatabaseByTableId($iTableId);

            foreach ($aFields as $iKey => $oField) {
                $aField = array(
                    'table_id' => $iTableId,
                    'sql_field' => $oField->Field,
                    'sql_type' => $oField->Type,
                    'sql_null' => $oField->Null,
                    'sql_key' => $oField->Key,
                    'sql_default' => $oField->Default,
                    'sql_extra' => $oField->Extra,
                    'allow_edit_in_list' => 0,
                    'ordering' => $iKey + 1
                );

                $iFieldId = $this->oModelTable->storeField($aField);

                if ($iFieldId == false) 
                {
                    return false;
                }
                
                $oDb = JFactory::getDbo();
                $oQuery = $oDb->getQuery(true);
                
                $iXMLTypeId = $this->oModelField->detectXMLType($iFieldId);
                if ($iXMLTypeId)
                {
                    $oQuery->clear()
                            ->update($oDb->quoteName('#__auto_field'))
                            ->set($oDb->quoteName('xml_type_id') . ' = ' . (int) $iXMLTypeId)
                            ->where($oDb->quoteName('id') . ' = ' . $oDb->quote($iFieldId));

                    $oDb->setQuery($oQuery);
                    try
                    {
                        $oDb->execute();
                    }
                    catch (RuntimeException $e)
                    {
                        JError::raiseWarning(500, $oDb->getMessage());
                        return false;
                    }
                }
            }

            $this->importMVC($iTableId);
        }
        
        return true;
    }

    public function importMVC($iTableId)
    {
        // Delete all old MVCs that exist in table.
        $sMessage = $this->oModelMVC->deleteAllMVC($iTableId);

        if ($sMessage !== true) {
            echo $sMessage;
            die;
        }

        // Get drap MVCs of the table.
        $aMVCs = $this->oModelMVC->getDrapMVC($iTableId);

        foreach ($aMVCs as $aMVC) {
            $this->oModelMVC->storeTable($aMVC);
        }
    }
    
    public function getSelectedTables()
    {
        return AutogeneratorHelper::getAllTablesByComponentId($this->oApplication->input->getInt('iComponentId'));
    }
}
